<?php

namespace app\api\controller\v32;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\AstroChange as AstroChangeModel;
use app\common\cachemodel\Fortune;
use app\common\cachemodel\GoddessArea;
use app\common\cachemodel\IndexButton;
use app\common\cachemodel\live\LiveBroadcastPreview;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\live\LiveSubscribe;
use app\common\cachemodel\lucky\AppLuckyTaskRecord;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\YearFortune;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZhunleCourse;
use app\common\cachemodel\ZlSynastryReport;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\ConfigManage;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AppNotice;
use app\common\model\Recode as RecodeModel;
use app\common\model\Slide;
use app\common\model\UserPush;
use Exception;
use think\Cache;
use think\Env;
use think\Log;

/**
 * @title 首页接口
 * @desc 首页改版
 * @version 2.8.5
 * Class Index
 * @package app\api\controller\v32
 */
class Index extends Auth2
{
    protected $restActionList = ['index'];

    protected $weekDay = [
        0 => '周日',
        1 => '周一',
        2 => '周二',
        3 => '周三',
        4 => '周四',
        5 => '周五',
        6 => '周六',
    ];

    /**
     * @title 首页接口
     * @method GET
     * @desc 无需另外传参
     * @readme /doc/api/index/index.md
     * @return string
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $isYoung = $this->user ? $this->user['young_model'] : false; // 是否是青少年模式
        $contentType = input('content_type/d', 2) === 2 ? 2 : 1;
        $time_now = time();
        $in_sign = input('in_sign/d', 1);
        $timezone = $this->headers['timezone'] ?? 8;
        $uid = $this->user ? (int)$this->user['id'] : null;
        if ($this->user && $this->user['rid'])
        {  // 开启青少年模式时，禁止访问幸运星
            $luckyNeedAuth = $isYoung ? 3 : 2;
            $astroCalendarNeedAuth = $isYoung ? 3 : 0;

            $map = ['uid' => $this->user['id'], 'isself' => 1];
            $recode_info = (new RecodeModel())->getSelfRecode($map);

            if (!$recode_info || !$recode_info['sun'])
            {
                return show(406, '档案缺失请添加档案');
            }

            $in_sign = explode('-', $recode_info['sun'])[0];
        } else
        {
            // 未登录，已选择星座用户，展示今日天象信息
            $luckyNeedAuth = 2;
            $astroCalendarNeedAuth = 0;
            if (!in_array($in_sign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
            {
                return show(408, '请选择星座');
            }
        }

        // 首页按钮
        $btns = (new IndexButton())->getIndexButton(['ver' => $this->headers['version'], 'app_type' => $this->headers['app-type']], true, $isYoung);
        //安卓开启审核模式时且是华为渠道,不展示占卜
        if ($this->android_audit_mode_swtich && stripos($this->headers['channel'], 'huawei') !== false)
        {
            foreach ($btns as $key => $btn)
            {
                if ($btn['type'] === 'divination_question')
                {
                    $link = preg_replace('/^divination_question.*/', "divination_question?type=0&name1='占星骰子'&need_auth=0", $btn['link']);
                    $btns[$key]['young_link'] = $btns[$key]['link'] = $link;
                }
            }
        }
        if ($isYoung)
        {
            $articles = null;
            $slide = null;
        } else
        {
            // 首页轮播
            $slide = (new Slide())->getSlideVersion([]);
        }

        //获取运势相关数据
        $revive_day = null;
        $fortune_cache = [];
        //若登录则计算今日运势获取三星数据
        if ($this->user['rid'])
        {
            try
            {
                $fortune_cache = (new Fortune())->fortuneDayHomeData($this->user['rid'], $time_now);
                //将今日运势图片替换为新图标
                $new_icon = explode('/', $fortune_cache['revive_day']['icon_url']);
                if (Util::CheckAppVersion('2.4.2') === '小')
                {
                    array_splice($new_icon, 5, 0, ['v2']);
                } else
                {
                    array_splice($new_icon, 5, 0, ['v3']);
                }
                $fortune_cache['revive_day']['icon_url'] = implode('/', $new_icon);
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                Log::write('首页获取日运缓存数据错误:' . 'uid=[' . $this->user['id'] . ']' . $e->getMessage(), 'error');
                throw new ApiException('服务异常，请稍后再试~');
            }
            //若今日运势为3级
            if ((int)($fortune_cache['revive_day']['star_level'] ?? 0) === 3)
            {
                $revive_day = $fortune_cache['revive_day'];
                $fortune_cache = [];//目录配置里层获取今日运势是否计算开关控制，$fortune_cache为空，则里层需要计算
            }
        }

        $date = gmdateModify('Y-m-d', time(), 8, $timezone);
        $birth = [];
        if ($this->user)
        {
            $userPush = (new UserPush())->getUserRegid($this->user['id']);
            $calendarBirthdayStatus = (int)($userPush['calendar_birthday_status'] ?? 1);
            if ($calendarBirthdayStatus === 1)
            {
                //获取用户今日生日信息
                $recodeData = (new \app\common\cachemodel\Recode())->userBirthMonthList($this->user, $date, $timezone);
                $host = Env::get('host.domain');
                $newMonth = gmdateModify('n-j', time(), 8, (float)$timezone);//当前时区的当前时间
                foreach ($recodeData as $recodeDatum)
                {
                    $recodeMonth = (int)$recodeDatum['month'];
                    $recodeDay = (int)$recodeDatum['day'];
                    //获取自己今日生日的信息
                    if ($recodeDatum['type'] == 1 && $newMonth == $recodeMonth . '-' . $recodeDay)
                    {
                        $birth = [
                            'text' => $recodeDatum['text'],
                            'target' => 'link',
                            'link' => $host . $recodeDatum['link']
                        ];
                        break;
                    }
                }
            }
        }
        //获取公告相关信息
        $AppNotice = new AppNotice();
        $notice = $AppNotice->getNewestNotice($birth, $uid);
        if ($notice && (!$isYoung || ($notice['young_model'] ?? false)))
        {   // 如果为开启青少年模式 或者 青少年模式下也显示
            $notice['content'] = $notice['des'];
            //公告为jpg或gif时算出向上偏移比例【算法：（图片居中时距上的高度 - 蓝狐所给距上的高度）/ 模板或手机的高度】保留两位
            if (in_array($notice['img_type'], [2, 3]))
            {
                $notice['img_top_height'] = -0.07;//图片距上高度比例 当img_type为2，3时存在，否则不存在,负数是向上偏移，正数是向下偏移
            }
            unset($notice['des'], $notice['young_model']);
        } else
        {
            $notice = null;
        }

        //获取首页目录配置信息
        $indexConfig = ConfigManage::indexCategoryV2($this->user, $in_sign, $this->headers['version'], $fortune_cache, $contentType);

        $luckyIsNew = $this->user ? (new AppLuckyTaskRecord())->getIndexIsNew($this->user['id']) : 0;

        $data = [
            'in_sign' => (int)$in_sign,
            'slides' => $slide,
            'buttons' => $btns,
            'fortune_category' => $indexConfig['fortune_category'],
            'article_category' => $indexConfig['article_category'],
            'lucky_planet_switch' => true,// 幸运星功能开关
            'notice' => $notice,
            'is_young_model' => $isYoung ? 1 : 2,
            'lucky_need_auth' => $luckyNeedAuth,
            'active_switch' => [
                'is_open' => false,
                'icon' => '',
                'target' => '',
                'link' => '',
                'width' => 0,
                'height' => 0
            ],
            'today_revive_day' => $revive_day,
            'astro_calendar' => [
                'target' => 'local',
                'link' => 'astro_calendar?date=' . $date . '&need_auth=' . $astroCalendarNeedAuth . '&umeng_event_name=common_target_link&umeng_event_label=' . urlencode('星象日历-首页顶部导航栏-点击')
            ],
            'astro_calendar_need_auth' => $astroCalendarNeedAuth,
            'area_list' => (new GoddessArea())->getHomeThemeData(),
            'week' => $this->weekDay[date('w')],
            'date' => date('m.d'),
            'year_fortune_new_icon_is_show' => 1,
            //  幸运星信息
            'lucky_info' => [
                'target' => 'local',
                'link' => 'lucky_star_home?need_auth=' . $luckyNeedAuth, //  青少年模式下 lucky_star_home?need_auth=3
                'is_new' => $luckyNeedAuth === 3 ? 0 : $luckyIsNew, // 当天未进行过签到或有幸运星待领取时，展示小红点
                'img' => 'https://oss.goddessxzns.com/test/lucky_star/lucky_star.png',
            ],
        ];
        $config = config('active.index_active');
        //若在活动时间内，开启
        if (active()['indexGift'] || ($time_now >= $config['start'] && $time_now <= $config['end']))
        {
            $data['active_switch'] = [
                'is_open' => false,
                'icon' => $config['icon'],
                'target' => 'link',
                'link' => Env::get('host.domain') . $config['link'],//大礼包h5
                'height' => 62
            ];
            // 仅针对V1.9.0和1.9.1开启首页幸运之城更新提示
            if (isset($this->headers['version']) && ($this->headers['version'] === '1.9.0' || $this->headers['version'] === '1.9.1'))
            {
                $data['active_switch']['is_open'] = true;
            }
        }

        // 登录后才做任务  VIP 每日任务
        if ($this->user)
        {
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 9);
        }

        $data['has_bind_tel'] = (($this->user['tel'] ?? '') || ($this->user['temporary_tel'] ?? '')) ? 1 : 0;
        $data['live_info'] = [];
        //青少年模式不展示直播
        if ($isYoung === false)
        {
            $isLiveIng = false; // 是否直播中
            $liveNative = 0;//1=>原生 0=>H5
            if (isset($this->headers['app-type']))
            {
                if ($this->headers['app-type'] === "ios" && Util::CheckAppVersion('2.7.3') !== '小')
                {
                    $liveNative = 1;
                }
                if ($this->headers['app-type'] === "android" && Util::CheckAppVersion('2.7.7') !== '小')
                {
                    $liveNative = 1;
                }
            }
            //获取直播预告信息
            $preview = (new LiveBroadcastPreview())->getNewestPreview();
            if ($preview)
            {
                $preview['record_id'] = (new LiveRecordingInfo())->getNewestRecord($preview['live_id']);
            }
            $recordId = (new LiveRecordingInfo())->getNewestRecord(0);
            $record = (new LiveRecordingInfo())->getInfoById($recordId);
            //直播中
            if (isset($record['status']) && (int)$record['status'] === 1)
            {
                $isLiveIng = true;
                //获取直播记录标题内容
                $data['live_info'] = [
                    'img' => $preview['broadcast_cover_img'] ?? '',
                    'title' => $record['title'],
                    'desc' => $record['content'],
                    'tips' => "",
                    'status' => 2,
                    'target' => 'local',
                    'link' => "live_web?live_id={$record['live_id']}&live_record_id={$record['id']}&live_native={$liveNative}&need_auth=0",
                ];
            } else if ($preview)
            {
                $timestamp = time();
                $three_timestamp = $preview['live_start_time'] - (3600 * 24);
                if ($preview['live_start_time'] > $timestamp && $three_timestamp < $timestamp)
                {
                    //若直播预约入口关闭则全不推送,若开启
                    $live_subscribe_status = 0;
                    if (isset($preview['subscribe_status']))
                    {
                        if ($preview['subscribe_status'])
                        {
                            if ($this->user)
                            {
                                $subscribeInfo = (new LiveSubscribe())->getUserSubscribeId($this->user['id'], $preview['id']);
                                if ($subscribeInfo && $subscribeInfo['status'] == 1)
                                {
                                    $live_subscribe_status = 1;
                                }
                            }
                        } else
                        {
                            $live_subscribe_status = 2;
                        }
                    }
                    $liveTime = date('n月d日 H:i', $preview['live_start_time']);
                    $data['live_info'] = [
                        'id' => $preview['id'],
                        'live_subscribe_status' => $live_subscribe_status,
                        'img' => $preview['broadcast_cover_img'],
                        'title' => $preview['broadcast_title'],
                        'desc' => $preview['broadcast_content'],
                        'tips' => "开播时间:{$liveTime}",
                        'status' => 1,
                        'target' => 'local',
                        'link' => "live_web?live_id={$preview['live_id']}&live_record_id=0&live_native=0&need_auth=0",
                    ];
                }
                //判断直播是否已开启
                $record = (new LiveRecordingInfo())->getInfoById($preview['record_id']);
                //直播中
                if (isset($record['status']) && (int)$record['status'] === 1)
                {
                    $isLiveIng = true;
                    //获取直播记录标题内容
                    $data['live_info'] = [
                        'img' => $preview['broadcast_cover_img'],
                        'title' => $record['title'],
                        'desc' => $record['content'],
                        'tips' => "",
                        'status' => 2,
                        'target' => 'local',
                        'link' => "live_web?live_id={$preview['live_id']}&live_record_id={$preview['record_id']}&live_native={$liveNative}&need_auth=0",
                    ];
                }
            }

            //若当前无公告框且预告直播间正在直播需要弹出公告框
            if (!$data['notice'] && $preview && $preview['notice_status'] && $isLiveIng === true)
            {
                $noticeInfo = json_decode($preview['extend'], true);
                if (!empty($noticeInfo['notice_info']))
                {
                    $data['notice'] = [
                        "id" => (int)('1000' . $preview['id']),
                        "type" => 1,//【1.弹一次； 2.每隔*天弹一次； 3.每次打开首页都弹一次； 4.每次都弹，不能关闭，没有关闭按钮（比如系统升级中等）；】
                        "sep_day" => 0, //每隔*天（当type=2时有效）
                        "img_url" => $noticeInfo['notice_info']['img_url'],
                        "img_width" => $noticeInfo['notice_info']['img_width'],
                        "img_height" => $noticeInfo['notice_info']['img_height'],
                        "img_type" => 1, //1=>默认白色背景的对话框 ，2=png/jpg(透明背景)，3=>gif（透明背景）
                        "img_top_height" => 0,//例如： -0.07，图片距上高度比例 当img_type为2，3时存在，否则不存在
                        "title" => $preview['broadcast_title'],
                        "content" => '',
                        "btn" => "点击进入直播间",
                        "target" => "local",
                        "link" => "live_web?live_id={$preview['live_id']}&live_record_id={$preview['record_id']}&live_native={$liveNative}&need_auth=0",
                    ];
                }
            }
        }
        return show(200, '首页加载成功', $data);
    }

    private function getTipCache()
    {
        $tipCacheKey = 'today_astro_tips:' . date('Ymd');

        $tip = Cache::get($tipCacheKey);

        if (!$tip)
        {
            $tip = $this->getTips();
            // 缓存今日天象信息
            Cache::set($tipCacheKey, $tip, 86400);
        }

        return $tip;
    }

    private function getTips()
    {
        //1、检测当天天象
        $astroChangeModel = new AstroChangeModel();
        $underwayAstro = $astroChangeModel->getChangeDayList(date('Y-m-d'), 8);

        if ($underwayAstro['listData'])
        {
            $strArray = [];
            foreach ($underwayAstro['listData'] as $v)
            {
                //若同时存在多天象，优先展示：太阳换座>X座新月>水星在X座逆行>金星X座逆行>金星进入X座>水星进入X座
                switch ($v['type'])
                {
                    case 1: // 行星换座
                        if ($v['pid'] == 0)
                        {
                            return $v['text']; // 太阳换座
                        }
                        if (in_array($v['pid'], [2, 3]))
                        {   // 水星 和 金星 换座
                            $strArray[strtotime($v['time']) + 1000000] = $v['text'];
                        }
                        break;
                    case 2: // 顺行 speed = 1｜ speed = 2逆行
                        if (in_array($v['pid'], [2, 3]) && $v['speed'] == 2)
                        { // 水星 和 金星 逆行
                            $strArray[strtotime($v['time'])] = $v['text'];
                        }
                        break;
                    case 5: // 新月
                        $strArray[strtotime($v['time']) - 1000000] = $v['text'];
                        break;
                    default:
                }
            }
            if ($strArray)
            {
                ksort($strArray);

                return current($strArray);
            }
        }
        // 如果今天没有重要天象 -> 则显示太阳运行在什么星座

        //2、X座新月（输出：某某座新月）
        //3、水、金是否逆行输出：某星逆行）
        //4、日水金是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、太阳在哪个星座（输出：太阳在某某座）
        // 若同时存在多天象，优先展示：太阳换座>X座新月>水星在X座逆行>金星X座逆行>金星进入X座>水星进入X座
        // 若无以上天象，则展示太阳运行在XX座
        $time = time();

        $timeinfo = ['year' => date('Y', $time), 'month' => date('m', $time), 'day' => date('d', $time), 'hour' => 0, 'minute' => 0,];

        $timeinfo['timezone'] = 8;

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0, $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;
        // 默认北京
        $timeinfo['longitude'] = 116.443153;
        $timeinfo['latitude'] = 39.921466;

        // 获取天象盘数据
        $nowData = Astrolog::getInstance()
            ->setExecPrefix(config('astrolog.prefix'))
            ->setAdvance($timeinfo)
            ->setUserSetting(config('astroset.setting1'))
            ->setGetDatas(['now'])
            ->getAstroDatas()
            ->getDatas('now');

        $tx_planet = is_array($nowData['planets']) ? $nowData['planets'] : json_decode(json_encode($nowData['planets'], true), true);// 天象行星数据

        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = Util::modSignId(floor($sun_deg / 30) + 1);
        $end_sign = Util::modSignId(floor(($sun_deg + $sun_speed) / 30) + 1);

        if ($start_sign == $end_sign)
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$start_sign])[3];

            $tip = '太阳运行在' . $sign_name;
        } else
        {
            $sign_name = explode('|', config('astrolog.sign_name')[$end_sign])[3];

            return '太阳进入' . $sign_name;
        }

        return $tip;
    }

    /**
     * 发现接口
     * @return \think\response\Json
     * @throws Exception
     */
    public function foundTool()
    {
        $oss = Env::get('host.photo');
        $isYang = $this->user['young_model'] ?? false;// 是否开启了青少年模式
        $rid = $this->user['rid'] ?? 0;

        //年运跳转 用户在本年11月至年底且并未解锁当前年， 点击解锁年运， 直接跳转至明年运势详情
        $yearTime = date('Y');
        $monthTime = date('m');
        $dayTime = date('d');
        //获取用户已解锁数据
        if ($rid)
        {
            $unlockYears = (new YearFortune())->getReocdeFortuneUnlockYears($rid);
            $unlockYears = array_map(function ($timeValue)
            {
                return (string)($timeValue);
            }, $unlockYears);

            $yearFortuneUnlockStatus = in_array($yearTime, $unlockYears, true) ? 1 : 0;
        } else
        {
            $yearFortuneUnlockStatus = 0;
        }

        if ($monthTime > 10 && $yearFortuneUnlockStatus === 0)
        {
            $yearTime = $yearTime + 1;
        } elseif ((int)$monthTime === 12 && $dayTime >= 10 && $yearFortuneUnlockStatus === 1)
        {
            $yearTime = $yearTime + 1;
        }

        $data = [
            [
                'title' => '',
                'list3' => [
                    [
                        'icon' => $oss . '/test/index/day.png',
                        'name' => '日运',
                        'target' => 'local',
                        'link' => 'day?rid=' . $rid . '&time=' . date('Y-m-d') . '&need_auth=' . ($isYang ? 3 : 1),
                        'desc' => '解锁单日运势'
                    ],
                    [
                        'icon' => $oss . '/test/index/month.png',
                        'name' => '月运',
                        'target' => 'local',
                        'link' => 'fortune_for_month?rid=' . $rid . '&time=' . date('Y-m') . '&need_auth=' . ($isYang ? 3 : 1),
                        'desc' => '解锁整月运势'
                    ],
                    [
                        'icon' => $oss . '/test/index/year.png',
                        'name' => '年运',
                        'target' => 'local',
                        'link' => 'fortune_for_year?rid=' . $rid . '&time=' . $yearTime . '&need_auth=' . ($isYang ? 3 : 1),
                        'desc' => '解锁整年运势'
                    ],
                ],
                'type' => 4
            ]
        ];

        if (!$this->is_apple_check)
        {
            $data = array_merge($data, [
                [
                    'title' => '心理测试',
                    'list' => [
                        [
                            'icon' => $oss . '/test/index/aq.png',
                            'name' => '',
                            'target' => 'local',
                            'link' => 'mental_test_list?page=mental_test_list&cid=1&sort=0&need_auth=' . ($isYang ? 3 : 2),
                        ],
                        [
                            'icon' => $oss . '/test/index/zy.png',
                            'name' => '',
                            'target' => 'local',
                            'link' => 'mental_test_list?page=mental_test_list&cid=3&sort=0&need_auth=' . ($isYang ? 3 : 2),
                        ],
                        [
                            'icon' => $oss . '/test/index/zh.png',
                            'name' => '',
                            'target' => 'local',
                            'link' => 'mental_test_list?page=mental_test_list&cid=0&sort=0&need_auth=' . ($isYang ? 3 : 2),
                        ],
                    ],
                    'type' => 1
                ], [
                    'title' => '定制报告',
                    'list2' => [
                        'icon' => $oss . '/test/index/custom_report2.png',
                        'img_width' => 1029,
                        'img_height' => 354,
                        'target' => 'local',
                        'link' => 'custom_report_index?need_auth=' . ($isYang ? 3 : 0),
                        'btn_info' => null,
                    ],
                    'type' => 3
                ]
            ]);
        }

        $data = array_merge($data, [
            [
                'title' => '一生报告',
                'list4' => $this->getNatalReport($isYang),
                'type' => 5
            ],
            [
                'title' => '幸运之城',
                'list2' => [
                    'icon' => $oss . '/test/index/acg_map.png',
                    'img_width' => 1029,
                    'img_height' => 450,
                    'target' => 'local',
                    'link' => 'acg_map?need_auth=' . ($isYang ? 3 : 1),
                    'btn_info' => [
                        'name' => '开启幸运之城',
                        'target' => 'local',
                        'link' => 'acg_map?need_auth=' . ($isYang ? 3 : 1),
                    ],
                ],
                'type' => 3
            ],
            [
                'title' => '校准生辰',
                'list2' => [
                    'icon' => $oss . '/test/index/rectification.png',
                    'img_width' => 1029,
                    'img_height' => 255,
                    'target' => 'local',
                    'link' => 'rectification?need_auth=' . ($isYang ? 3 : 0),
                    'btn_info' => null,
                ],
                'type' => 3
            ],
            [
                'title' => '万幸商城',
                'list2' => [
                    'icon' => $oss . '/test/index/mall.png',
                    'img_width' => 1029,
                    'img_height' => 270,
                    'target' => 'local',
                    'link' => 'mall_store_goods_list?need_auth=' . ($isYang ? 3 : 0),
                    'btn_info' => null,
                ],
                'type' => 3
            ],
        ]);

        if (Env::get('host.name') !== 'online')
        {//开发环境
            $data[] = [
                'title' => '实用工具',
                'type' => 2,
                'list' => [
                    [
                        'icon' => $oss . '/test/index/zyxp.png',
                        'name' => '专业星盘',
                        'target' => 'local',
                        'link' => 'astrolable?need_auth=1',
                    ],
                    [
                        'icon' => $oss . '/test/index/xzsc.png',
                        'name' => '校准生辰',
                        'target' => 'local',
                        'link' => 'rectification?need_auth=' . ($isYang ? 3 : 1),
                    ],
                    [
                        'icon' => $oss . '/test/index/twjh.png',
                        'name' => '提问解惑',
                        'target' => 'local',
                        'link' => 'divination_question?type=2&name1=%E5%8D%A0%E6%98%9F%E9%AA%B0%E5%AD%90&name2=%E5%A1%94%E7%BD%97%E5%8D%A0%E5%8D%9C&need_auth=' . ($isYang ? 3 : 0),
                    ],
                    [
                        'icon' => $oss . '/test/index/txrl.png',
                        'name' => '天象日历',
                        'target' => 'local',
                        'link' => 'astro_calendar?date=' . date("Y-m-d") . '&need_auth=' . ($isYang ? 3 : 1),
                    ],
                ]
            ];

            $data[] = [
                'title' => '玩转星座',
                'list' => [
                    [
                        'icon' => $oss . '/test/index/xyzc.png',
                        'name' => '幸运之城',
                        'target' => 'local',
                        'link' => 'acg_map?need_auth=' . ($isYang ? 3 : 1),
                    ],
                    [
                        'icon' => $oss . '/test/index/gxhp.png',
                        'name' => '关系合盘',
                        'target' => 'local',
                        'link' => 'composite?need_auth=1',
                    ],
                    [
                        'icon' => $oss . '/test/index/hdxw.png',
                        'name' => '互动星文',
                        'target' => 'local',
                        'link' => 'articles?need_auth=' . ($isYang ? 3 : 0),
                    ],
                    [
                        'icon' => $oss . '/test/index/xyx.png',
                        'name' => '幸运星',
                        'target' => 'local',
                        'link' => 'lucky_star_home?need_auth=' . ($isYang ? 3 : 0),
                    ],
                    [
                        'icon' => $oss . '/test/index/ysbj.png',
                        'name' => '运势日记',
                        'target' => 'local',
                        'link' => 'fortune_day_note?need_auth=' . ($isYang ? 3 : 1),
                    ],
                ],
                'type' => 2
            ];
        }

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * @param $isYang
     * @return array|array[]|\think\response\Json
     * @throws \think\Exception
     */
    private function getNatalReport($isYang)
    {
        $oss = Env::get('host.photo');
        $rid = $this->user['rid'] ?? 0;
        $uid = $this->user['id'] ?? 0;
        $NatalReportModel = new \app\common\cachemodel\NatalReport();

        $unlockReport = [];
        //获取商品类型
        $goodData = (new NatalGoods())->getGoods();
        if ($uid && $rid)
        {
            $recode = (new RecodeModel())->getRecode(['id' => $rid]);
            if (!$recode || (int)$recode['uid'] !== $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
            // 判断当前解锁状态
            $unlockReport = $NatalReportModel->getNatalReport2($recode);
        }
        // 未解锁 或 解锁中
        $orderModel = new \app\common\cachemodel\Orders();
        $activingModel = new ZhunleActivity();
        // 获取合盘报告商品
        if (Util::getSynastryReportSwitch() && Util::CheckAppVersion('2.5.2') !== '小')
        {
            $synastryReportGoods = (new \app\common\cachemodel\Goods())->GoodsTypeInfo(17);
            $goodData = array_merge($synastryReportGoods, $goodData);
        }
        //获取报告商品图片
        $reportImage = [
            'synastry_report' => $oss . '/test/index/synastry_report.png',//大图
            'feelings' => $oss . '/test/index/feelings.png',  //
            'dating' => $oss . '/test/index/dating.png',// 婚姻报告new图
            'money' => $oss . '/test/index/money.png',
            'carrer' => $oss . '/test/index/carrer.png',
            'academic' => $oss . '/test/index/academic.png',// 学业报告限时9折图片
        ];
        foreach ($goodData as $key => $item)
        {
            $item['id'] = isset($item['id']) ? (int)$item['id'] : 0;
            $discount_price = null;
            $timeRange = null;
            $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;
            $unlockGid = $goodType === 17 ? $item['srid'] : $item['id'];
            $unlockNumber = $orderModel->getTotalPrepaidOrder($goodType, $unlockGid);
            // 获取活动商品信息
            $activing = $activingModel->getActivingGood($goodType, $item['id']);
            if ($activing)
            {
                $timeRange = $activing['end_time'] - time();
            }


            if ((int)$item['status'] !== 2)
            {
                if ($goodType === 17)
                {
                    // 检测 是否购买过
                    if ($uid)
                    {
                        if ($rid)
                        {
                            $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($uid, $rid, 0, $item['srid']);
                            $unlock_status = $unlockStatus ? 2 : 0;
                        } else
                        {
                            $ids = (new ZlSynastryReport)->getSynastryReportIds($uid, 0, 0, $item['srid']);
                            $unlock_status = $ids ? 2 : 0;
                        }
                    } else
                    {
                        $unlock_status = 0;
                    }
                } else
                {
                    if (isset($unlockReport[$item['id']]))
                    {
                        if ((int)$unlockReport[$item['id']]['status'] === 2)
                        {
                            $unlock_status = 2;//已解锁
                        } else
                        {
                            $unlock_status = 1;//计算中
                        }
                    } else
                    {
                        $unlock_status = 0;//未解锁
                    }
                }
            } else
            {
                $unlock_status = 3;//未开放
            }
            if ($goodType === 17)
            {
                $d['synastry_report'] = [
                    'gid' => $item['id'],
                    'status' => $unlock_status,
                    'bg_img' => $reportImage['synastry_report'] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $item['name'] ?? '',
                    'unlock_num' => $item['base_num'] + $unlockNumber,
                    'active_time' => $timeRange ?? 0,
                    'target' => 'local',
                    'link' => $unlock_status === 0 ?
                        "synastry_report_detail?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=" . ($isYang ? 3 : 1) :    // 下单介绍页
                        "synastry_report_list?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=" . ($isYang ? 3 : 1)  // 查看合盘报告列表
                ];
            } else
            {
                $d[$item['flag']] = [
                    'gid' => $item['id'],
                    'status' => $unlock_status,
                    'bg_img' => $reportImage[$item['flag']] ?? '',
                    'gcolor' => $item['color'] ?? '',
                    'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                    'unlock_num' => $item['base_num'] + $unlockNumber,
                    'active_time' => $timeRange ?? 0,
                    'target' => 'local',
                    'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=" . ($isYang ? 3 : 1)
                ];
            }
        }

        return [
            $d['synastry_report'],
            $d['dating'],
            $d['feelings'],
            $d['money'],
            $d['academic'],
            $d['carrer'],
        ];
    }
}
